<!DOCTYPE html>
<html>
<head>
    <title>限时课程开课</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div>
        <h2>限时课程开课</h2>
        <hr>
        <div class="form-row">
            <h4 style="width:80px;">会员姓名</h4><input id='cusNameInput' style="width:100px;" oninput="handleCusNameInput()">
        </div>
        <div id="cusList" style="display:none;"></div>
        <div id="currentClass"></div>

        <div class="form-row">
            <h4 style="width:80px;">课程名称</h4><select id='clsNameSel' onchange="getBuyCodeList()"></select>
        </div>

        <div id="openInsBlock" class="form-row">
        <h4 style="width:80px;">开课人</h4>
        <select id="insSelect">            
        </select>
        
        </div>

        <div id="cusNameBelowDivs" style="display:none;">
            <div  id="startType"  class="form-row">
                <h4 style="width:80px;">开课方式</h4>
                <h4 style="width:200px;margin-left:0px;">
                <label for="startTypeRadio"></label>
                <input type="radio" name="startTypeRadio" value="新课" onclick="getBuyCodeList()" checked>开启新课
                <input type="radio" name="startTypeRadio" value="延长" onclick="getBuyCodeList()">延长旧课
                </h4>
                
            </div>
            <hr>
        
            <div id="currentValidLmtCls"></div>

            <!-- <div id="buyHistoryPrompt"  style="display:none">选择相应的购课编码</div> -->
            <div id="selectCardBlock" class="form-row">
                <h4 style="width:120px;">请选择关联卡号 </h4>
                <select id="selectBuyCodeContainer" style="display:none;margin:10px;"> 
                <option value="">--请选择关联卡号--</option>
                </select>            
            </div>
            
            <div id="clsLongBlock" style="display:none;margin:10px;"><h4>购课时长：
                <span id="clsLong"></span> 天</h4>
            </div>

            <div id="validTimeBlock" style="display:none;margin:10px;"><h4>有效上课时段：
                <span id="validTime"></span> </h4>
            </div>
            

            <div id='startDateBlock' class='form-row'  style="display:none;">
                <h4 style="width:70px;">开课日期</h4><input id="startDate" type="date" > 
            </div>          

            <div id='endDateBlock' class='form-row' style="display:none;"><h4 style="width:70px;">结束日期</h4><input id="endDate" type="date" >（不包括该日期）</div>
            <div id='endDatePrompt'></div>
            <!-- <div style="margin:10px;"></div> -->
            <br>
            <div id="showDealResult" style="display:none;margin:10px;">正在处理……</div>
            <div id="prompt"></div>
            <hr>
            <button id="submit" onclick="submit()" style="display:none;margin:10px;">开课</button>
        </div>
    </div>

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script> 
        let cus_list;
        let tmplt_info;
        let cls_types;
        let not_start_buy_code_list;
        let limit_cls_recs;
        let buy_list;
        let valid_limit_class_rec;
        let latest_limit_class_rec;
        let ins_list;
        let insName;
        let insId;
        let insRole;
        let isInValidEndDateHandler;
        let isInValidEndDateNewHandler;
        let isInValidStartDateHandler;
        let clsQty={};

        // 使用DOMContentLoaded事件监听，在页面加载完成后触发获取数据的操作
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();

            insInfo=hideInsSelectBlockAndGetInsInfo('openInsBlock');
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];
            
            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            selectToday(id='startDate',format='date');
            const startDate=document.getElementById('startDate')
            // const endDate=document.getElementById('endDate');
            selectDate(dateToString(calculateDate(startDate.value,1),'date'),'endDate','date');

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;        
                console.log('template infos:',tmplt_info); 
                generateClsName(data['cls_type_name_dic']['限时课程']);
                  })
                .catch(error => console.error('Error:', error));

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                cus_list=data
                // console.log(cus_list);
                  })
                .catch(error => console.error('Error:', error));       
                
            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // ins_list=data
                console.log('ins_list:',data)
                generateInsList(data.ins_list,'insSelect');
                // console.log(cus_list);
                  })
                .catch(error => console.error('Error:', error));    
            
        });

        function generateClsName(clsNames){
            const clsNameSel=document.getElementById('clsNameSel');
            clsNames.forEach(cls=>{
                const opt=document.createElement('option');
                opt.value=cls;
                opt.textContent=cls;
                clsNameSel.appendChild(opt);
            });
        }
        

        function checkSubmit(){
            const buyCode=document.getElementById('selectBuyCodeContainer').value;
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;
            const startType=document.querySelector('input[name="startTypeRadio"]:checked').value;
            const insNameSelect=document.getElementById('insSelect').value;
            if(startType==='新课'){
                const compareDate=new Date(endDate)-new Date(startDate);
                    if(compareDate<=0){
                        return '选择的结束日必须在开始日之后';
                    }
            }
            
            // const compareDate=new Date(endDate)-new Date(latestValidEndDate);
            if(buyCode===''||startDate===''||endDate===''){
                
            }
            if(insName==='admin' && insNameSelect===''){
                return '有未选择项目';
            }
            
            
            return 'OK';
        }

        function submit(){
            const cusName=document.getElementById('cusNameInput').value;
            const checkValidResult=checkSubmit();
            const startType=document.querySelector('input[name="startTypeRadio"]:checked').value;
            const clsName=document.getElementById('clsNameSel').value;
            let insIdSend;
            if(checkValidResult==='OK'){
                document.getElementById('showDealResult').style.display='block';
                if(insRole==='admin'){
                    insIdSend=document.getElementById('insSelect').value;
                }else if(insRole==='ins'){
                    insIdSend=insId;
                }else{
                    insIdSend=insId;
                }
                // console.log(insId,document.getElementById('insSelect').value)
                data={
                    'cus_name_input':cusName,
                    'card_id':document.getElementById('selectBuyCodeContainer').value,
                    'card_type':'限时课程',
                    'cls_name':clsName,
                    'start_date':document.getElementById('startDate').value,
                    'end_date':document.getElementById('endDate').value,
                    'valid_time':document.getElementById('validTime').textContent==='正常营业时间'?'all_day':document.getElementById('validTime').textContent.replace(/:/g,''),
                    'ins_id':insIdSend,
                    'opr_id':insId,
                    'opr_type':startType,
                    'prd':document.getElementById('clsLong').innerText,
                    'cls_qty':clsQty[document.getElementById('selectBuyCodeContainer').value]
                }

                console.log(data);
                fetch('/deal_start_class_page',{
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body:JSON.stringify(data)
                })
                .then(response=>response.json())
                .then(data=>{
                    // console.log(data['result']);
                    // location.reload();
                    const btnText=document.getElementById('submit').textContent;
                    if(btnText==='开课'){
                        alert("开课成功");
                    }else{
                        alert("延期成功");
                    }
                    
                    window.location.replace('./index');
                })
                .catch(error=>{
                    console.error('写入限时课程表或辅助表出错:',error);
                });
            }else{
                alert(checkValidResult)
            }
        }

        function formatTimeRange(timeStr) {
            // 1. 分割字符串，获取开始和结束时间
            const [start, end] = timeStr.split('-');
            
            // 2. 格式化时间（补全冒号）
            const formatTime = (time) => {
                const hours = time.slice(0, 2);  // 取前两位作为小时
                const minutes = time.slice(2);   // 取后两位作为分钟
                return `${hours}:${minutes}`;
            };
            
            // 3. 拼接成最终格式
            return `${formatTime(start)}-${formatTime(end)}`;
        }
   
        function dateFormat(inputDate){
            const dateString = inputDate;
            const dateObj = new Date(dateString);
            const formattedDate = toBeijingTimeString(dateObj);
            return formattedDate
        }        

        function getBuyCodeList(cusName=''){
            if(cusName===''){
                cusName=document.getElementById('cusNameInput').value;
            }
            const clsName=document.getElementById('clsNameSel').value;
            const selectCardBlock=document.getElementById('selectCardBlock');
            const selectBuyCodeContainer=document.getElementById('selectBuyCodeContainer');
            const buyHistoryPrompt=document.getElementById('buyHistoryPrompt');
            const startDateBlock=document.getElementById('startDateBlock');
            const endDateBlock=document.getElementById('endDateBlock');
            const startDateSel=document.getElementById('startDate');
            const endDateSel=document.getElementById('endDate');
            const clsLongBlock=document.getElementById('clsLongBlock');
            const clsLong=document.getElementById('clsLong');
            const validTimeBlock=document.getElementById('validTimeBlock');
            const validTime=document.getElementById('validTime');
            


            clsLong.innerText='';
            const currentValidLmtCls=document.getElementById('currentValidLmtCls');
            currentValidLmtCls.innerText='';
            const prompt = document.getElementById('prompt');
            prompt.innerText='';
            const endDatePrompt = document.getElementById('endDatePrompt');
            endDatePrompt.innerText='';
            const startType=document.querySelector('input[name="startTypeRadio"]:checked').value;
            const submitButton=document.getElementById('submit');
            submitButton.style.display='none';
            const currentClassResult=document.getElementById('currentClass')
            currentClassResult.style.display='none';
            selectBuyCodeContainer.style.display='none';
            selectBuyCodeContainer.innerHTML='<option value="">--请选择购课编码--</option>';
            startDateBlock.style.display='none';
            endDateBlock.style.display='none';
            validTimeBlock.style.display='none';


            fetch('/send_to_start_lmt_page_data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify({'cus_name':cusName})
                })
                .then(response => response.json())
                .then(data => {
                    console.log('all lmt infos:',data)
        
                    if(data['res']==='ok'){
                        //目前有限时有效课，有待开 or 有限时有效课，无待开 —— 均不可开新课，但可以延长
                        if(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'].length>0 && data['lmt_cls_infos'][clsName]['not_start_limit_recs'].length>0 || data['lmt_cls_infos'][clsName]['current_valid_limit_rec'].length>0 && data['lmt_cls_infos'][clsName]['not_start_limit_recs'].length===0){
                            clsQty={};
                            if(startType==='新课'){
                                endDatePrompt.innerText='';
                                const showEndDate=new Date(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][3]);
                                showEndDate.setDate(showEndDate.getDate()-1);
                                currentValidLmtCls.innerHTML=`<p>目前有限时课程生效</p><p>卡号：${data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][0]}</p><p>有效期至${dateToStringGmt(showEndDate,'date')}，剩余${(parseInt(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][6])).toFixed(0)}节。</p>`;
                                clsLongBlock.style.display='none';
                                selectCardBlock.style.display='none';
                                prompt.innerText='没有待开课的限时课程'
                            }else if(startType==='延长'){
                                selectCardBlock.style.display='block';
                                selectBuyCodeContainer.style.display='block';
                                startDateBlock.style.display='flex';
                                endDateBlock.style.display='flex';
                                currentClassResult.style.display='block';
                                submitButton.style.display='block';
                                clsLongBlock.style.display='block';
                                clsLong.innerText=parseInt(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][2]);
                                validTimeBlock.style.display='block';
                                validTime.innerText= data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][7]==='all_day'?'正常营业时间':formatTimeRange(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][7]);

                                selectBuyCodeContainer.innerHTML='';                                
                                const cardOpt=document.createElement('option');
                                cardOpt.value=data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][0];
                                cardOpt.text=data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][0];
                                selectBuyCodeContainer.append(cardOpt);
                                selectDate(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][1],'startDate','date');
                                startDateSel.disabled=true;
                                selectDate(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][3],'endDate','date');   
                                clsQty[data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][0]]=data['lmt_cls_infos'][clsName]['current_valid_limit_rec'][0][4]; 
                                //验证结束日的有效性，为避免重复添加监听，先移除之前的监听器。
                                //只有监听器保存在全局变量isInValidEndDateHandler的闭包中才能正确移除。
                                if(isInValidEndDateHandler){
                                    endDateSel.removeEventListener('change',isInValidEndDateHandler);
                                }
                                isInValidEndDateHandler = createEndDateHandler(data['lmt_cls_infos'][clsName], 'current_valid_limit_rec');                                
                                endDateSel.addEventListener('change',isInValidEndDateHandler);                                
                                //手动触发change
                                // selectBuyCodeContainer.dispatchEvent(new Event('change'));    
                                // endDateSel.dispatchEvent(new Event('change'));  变量。                      
                            }
                            
                        //目前 无限时有效课，有待开——可开新课，不可延长
                        }else if(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'].length===0 & data['lmt_cls_infos'][clsName]['not_start_limit_recs'].length>0){
                            clsQty={};
                            if(startType==='新课'){
                                prompt.innerText=''
                                selectCardBlock.style.display='block';   
                                selectBuyCodeContainer.style.display='block';           
                                clsLongBlock.style.display='block';
                                validTimeBlock.style.display='block';
                                startDateBlock.style.display='flex';
                                endDateBlock.style.display='flex';
                                currentClassResult.style.display='block';
                                submitButton.style.display='block';
                                selectBuyCodeContainer.innerHTML='';
                                let notStartClsInfo=[];
                                let prds={};
                                data['lmt_cls_infos'][clsName]['not_start_limit_recs'].forEach(rec=>{
                                    const cardOpt=document.createElement('option');
                                    cardOpt.value=rec[0];
                                    cardOpt.text=rec[0];
                                    selectBuyCodeContainer.append(cardOpt);
                                    prds[rec[0]]=rec[2];
                                    clsQty[rec[0]]=rec[4];
                                    
                                });

                                
                                selectBuyCodeContainer.addEventListener('change',function(){
                                    const cardId=document.getElementById('selectBuyCodeContainer').value;        
                                    for(i=0;i<data['lmt_cls_infos'][clsName]['not_start_limit_recs'].length;i++){
                                        if(data['lmt_cls_infos'][clsName]['not_start_limit_recs'][i][0]===cardId){
                                            const today=new Date();
                                            selectDate(today,'startDate','date');
                                            // startDateSel.disabled=true;
                                            const endDate=calculateDate(document.getElementById('startDate').value,parseInt(data['lmt_cls_infos'][clsName]['not_start_limit_recs'][i][2]));
                                            // console.log(endDate)
                                            selectDate(endDate,'endDate','date');
                                            clsLong.innerText=parseInt(data['lmt_cls_infos'][clsName]['not_start_limit_recs'][i][2]);                                            
                                            validTime.innerText= data['lmt_cls_infos'][clsName]['not_start_limit_recs'][i][5]==='all_day'?'正常营业时间':formatTimeRange(data['lmt_cls_infos'][clsName]['not_start_limit_recs'][i][5]);
                                            break;
                                        }
                                    }
                                    
                                });

                                //课程开始日校验
                                if(isInValidStartDateHandler){
                                    startDateSel.removeEventListener('change',isInValidStartDateHandler);
                                }                    
                                isInValidStartDateHandler = createInValidStartDateHandler(prds);                                
                                startDateSel.addEventListener('change',isInValidStartDateHandler);  
                                
                                
                                //课程结束日校验
                                if(isInValidEndDateNewHandler){
                                    endDateSel.removeEventListener('change',isInValidEndDateNewHandler);
                                }
                                isInValidEndDateNewHandler = createEndDateNewHandler(prds);                                
                                endDateSel.addEventListener('change',isInValidEndDateNewHandler);    


                                //手动触发change
                                selectBuyCodeContainer.dispatchEvent(new Event('change'));    
                                // endDateSel.dispatchEvent(new Event('change'));                       
                                   
                            }else if(startType==='延长'){
                                prompt.innerText='没有可延长的限时课程';
                                endDatePrompt.innerText='';
                                selectCardBlock.style.display='none';
                                clsLongBlock.style.display='none';
                                startDateBlock.style.display='none';
                                endDateBlock.style.display='none';
                                currentClassResult.style.display='none';
                                submitButton.style.display='none';                                                      
                            }

                        }
                        //目前 无限时有效课，无待开——不可开新课，不可延长
                        else if(data['lmt_cls_infos'][clsName]['current_valid_limit_rec'].length===0 & data['lmt_cls_infos'][clsName]['not_start_limit_recs'].length===0){
                            clsQty={};
                            selectCardBlock.style.display='none';
                            startDateBlock.style.display='none';
                            clsLongBlock.style.display='none';
                            endDateBlock.style.display='none';
                            currentClassResult.style.display='none';
                            submitButton.style.display='none';
                            endDatePrompt.style.display='block';
                            if(startType==='新课'){
                                prompt.innerText='没有可开的限时课程';
                            }else if(startType==='延长'){
                                prompt.innerText='没有可延长限时课程';
                            }
                            
                        }
                    }

                    const btn=document.getElementById('submit');
                    if(startType==='新课'){                        
                        btn.textContent='开课';
                    }else{
                        btn.textContent='延长';
                    }
                })         
                
                .catch(error => console.error('Error:', error));

            
        }

        function createInValidStartDateHandler(prds){
            return function(){
                isInValidStartDate(prds);
            }
        }

        function isInValidStartDate(prds){
            
            const _today=new Date();
            const today = new Date(_today.getFullYear(), _today.getMonth(), _today.getDate());
            const startDateSel=document.getElementById('startDate');
            startDateSel.disabled=false;
            const endDateSel=document.getElementById('endDate');
            const selectBuyCodeContainer=document.getElementById('selectBuyCodeContainer');   
            const cardId=selectBuyCodeContainer.value;
            const selectStartDate=new Date(startDateSel.value);        
            const selectEndDate=endDateSel.value;            
            const endDatePrompt=document.getElementById('endDatePrompt');            

            if(new Date(selectStartDate.getFullYear(), selectStartDate.getMonth(), selectStartDate.getDate())<today){
                
                selectDate(today,'startDate','date');
                endDatePrompt.innerText='选择的开始日不能早于今天，已修改。';
            }else{
                endDatePrompt.innerText='';
            }
            const endDateRes=calculateDate(startDateSel.value,parseInt(prds[selectBuyCodeContainer.value]))
            // console.log(endDateRes)
            selectDate(endDateRes,'endDate','date');
            

        }
        

        function createEndDateNewHandler(prds) {
            return function(){
                isInValidEndDateNew(prds)
            };
        }

        function isInValidEndDateNew(prds){     
            
            const startDateSel=document.getElementById('startDate');
            const endDateSel=document.getElementById('endDate');
            const selectBuyCodeContainer=document.getElementById('selectBuyCodeContainer');   
            const cardId=selectBuyCodeContainer.value;
            const selectStartDate=startDateSel.value;
            const selectEndDate=endDateSel.value;
            const cardEndDate=calculateDate(startDateSel.value,parseInt(prds[selectBuyCodeContainer.value]));
            const endDatePrompt=document.getElementById('endDatePrompt');

            // console.log(selectEndDate,cardEndDate)
            
            if(new Date(selectEndDate)<new Date(cardEndDate)){                
                selectDate(cardEndDate,'endDate','date');
                endDatePrompt.innerText='选择的结束日不能小于卡结束日，已修改为卡结束日。';
            }else{
                endDatePrompt.innerText='';
            }
        }



        function createEndDateHandler(data,item) {
            return function(){
                isInValidEndDate(data,item)
            };
        }

        function isInValidEndDate(data,item){     
            // console.log(event,data,item)
            const startDateSel=document.getElementById('startDate');
            const endDateSel=document.getElementById('endDate');
            const selectBuyCodeContainer=document.getElementById('selectBuyCodeContainer');   
            const cardId=selectBuyCodeContainer.value;
            const selectStartDate=startDateSel.value;
            const selectEndDate=endDateSel.value;
            const cardEndDate=data[item][0][3];
            const endDatePrompt=document.getElementById('endDatePrompt');
            
            if(new Date(selectEndDate)<new Date(cardEndDate)){                
                selectDate(cardEndDate,'endDate','date');
                endDatePrompt.innerText='选择的结束日不能小于卡结束日，已修改为卡结束日。';
            }else{
                endDatePrompt.innerText='';
            }
        }

        function handleCusNameInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");
            const submitButton=document.getElementById('submit');
            document.getElementById("cusNameBelowDivs").style.display="none";
            document.getElementById("currentClass").style.display="none";
            submitButton.style.display="none";


            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusNameInput").value = name;
                        document.getElementById("cusNameBelowDivs").style.display="block";

                        resultList.style.display = "none";
                        // getBuyList(name);
                        getBuyCodeList(name);
                        // 手动触发change事件
                        // nameInput.dispatchEvent(new Event('change'));
                        // 清空结果列表

                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });
        
            resultList.classList.add("cus-list-result-blue");
            resultList.style.top='138px';
            resultList.style.left='228px';
            
        }
     

    </script>
</body>
</html>
